import numpy as np
import pandas as pd
import os
import time
import glob
import re
import warnings
from program.pack.append_df_to_excel import append_df_to_excel
from pandas import to_datetime
from functools import reduce
import shutil

warnings.filterwarnings("ignore")

# 列显示不全，进行设置
pd.set_option('display.max_columns', 500)
pd.set_option('display.unicode.ambiguous_as_wide', True)
pd.set_option('display.unicode.east_asian_width', True)
pd.set_option('display.width', 180)  # 设置打印宽度(**重要**)


def df_pic():
    dic_pic = {}
    path_pic = r'E:\样品汇总'  # 图片地址
    for root_dirs, sub_dirs, files in os.walk(path_pic):
        for file_pic in files:
            if (file_pic.lower().startswith('~$') is False) and (file_pic.lower().endswith('.jpg')):
                file_path = os.path.join(root_dirs, file_pic)
                dic_pic[file_pic] = file_path
    df_pic = pd.DataFrame({
        '图片名': [item.upper() for item in list(dic_pic.keys())],
        '图片地址': list(dic_pic.values()), })
    return df_pic


def func_0x(path_inputs=[r'I:\Data\0513新疆机场3'], endswith_false='Data.xlsx', endswith='.xlsx'):
    data_pic = df_pic()
    dic_pic_num = {}
    data_error = pd.DataFrame(columns=['文件夹地址', '图片名'])
    i = 0
    for path_input in path_inputs:  # 支持多文件夹遍历
        # os.walk(file_path) 深度遍历file_path下的所有子文件夹及文件
        for root_dirs, sub_dirs, files in os.walk(path_input):
            # 读取xlsx,以key_id为键
            for file in files:
                # 进行条件筛选   以非~$'开头(解决读取文档已打开问题)；选择以file_name_0结尾的文档
                if (file.startswith('~$') is False) and (file.endswith('.xlsx')) and (
                        file.lower().endswith('data.xlsx') is False):
                    # 构造文件的绝对路径 = 文件夹路径 + 文件名
                    num = 0
                    for a, b, c in os.walk(root_dirs):
                        for l in c:

                            if 'jpg' in l or 'JPG' in l:
                                num += 1
                            else:
                                pass
                    dic_pic_num[root_dirs] = num
                    try:
                        file_path = os.path.join(root_dirs, file)
                        data_1 = pd.read_excel(file_path)
                        pic = data_1.iloc[4, 1].upper() + '.JPG'
                        # os.walk(file_path) 深度遍历file_path下的所有子文件夹及文件
                        # print(root_dirs, pic)
                        file_path_new = os.path.join(root_dirs, pic)
                        if pic in data_pic['图片名'].values:
                            file_path_pic = data_pic.loc[data_pic['图片名'] == pic, '图片地址'].values[0]
                            print('jpg路径：', file_path_pic, '\n', 'to:', file_path_new)
                            shutil.copy(file_path_pic, file_path_new)
                        elif pic not in data_pic['图片名'].values:
                            i += 1
                            data_error.loc[i] = [root_dirs, pic]
                    except Exception as e:
                        print(root_dirs, e)
    print(data_error)
    dic_pic_num = pd.DataFrame({
        '文件地址': [item for item in list(dic_pic_num.keys())],
        '图片数量': list(dic_pic_num.values()), })
    print(dic_pic_num)
    # 找不到样品图片数据      文件夹下图片数量
    append_df_to_excel(r'../program2.5/data_error2.xlsx', data_error, sheet_name='data', startcol=0, startrow=0,
                       index=False)
    append_df_to_excel(r'../program2.5/data_error2.xlsx', dic_pic_num, sheet_name='pic_num', startcol=0, startrow=0,
                       index=False)


if __name__ == "__main__":
    # 记录时间
    start = time.time()
    # 数据源地址
    paths = r'I:\TAI40-II对比测试'
    path_inputs = [paths]
    func_0x(path_inputs, endswith_false='Data.xlsx', endswith='.xlsx')
